
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:p_location/common/constant/color_list.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/common/widget/expand_or_collapse_view.dart';
import 'package:p_location/common/widget/no_result_widget.dart';
import 'package:p_location/home/constant/home_http_url.dart';
import 'package:p_location/home/obj/tree_node_cache_info.dart';
import 'package:p_location/home/res/home_tab_area_detail_obj.dart';
import 'package:p_location/home/res/home_tab_area_info_res.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_listener_impl.dart';

import 'home_tab_area_item_widget.dart';

GlobalKey<_HomeTabAreaInfoWidgetState> areaInfoKey = GlobalKey();

class HomeTabAreaInfoWidget extends StatefulWidget {
  @override
  _HomeTabAreaInfoWidgetState createState() => _HomeTabAreaInfoWidgetState();

  HomeTabAreaInfoWidget({Key key}) : super(key: key);
}

class _HomeTabAreaInfoWidgetState extends State<HomeTabAreaInfoWidget> {
  bool isLoading = true;

  bool isRequesting = false;

  List<HomeTabAreaDetailObj> origins = [];
  List<HomeTabAreaDetailObj> infoList = [];

  // 缓存的 结点状态信息 用于刷新
  List<TreeNodeCacheInfo> cacheList = [];

  bool expandFlag = false;
  int threshold = 4;

  @override
  void initState() {
    super.initState();
//    _requestAreaInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 8, right: 8, top: 5),
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(bottom: 5),
            alignment: Alignment.centerLeft,
            child: Text(" 区域统计"),
          ),
          Card(
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              padding: EdgeInsets.only(bottom: 2),
              child: Column(children: [
                Flex(direction: Axis.horizontal, children: [
                  _getTabItem("区域名称"),
                  _getTabItem("人数"),
                  _getTabItem("车辆")
                ]),
                FractionallySizedBox(
                    widthFactor: 1,
                    child: Container(
                      child: Text("1"),
                      color: Colors.grey[200],
                      height: 0.5,
                    )),
                Container(
                  color: Colors.white,
                  child: Stack(
                    children: <Widget>[_getContentView()],
                  ),
                )
              ]),
            ),
          )
        ],
      ),
    );
  }

  _getContentView() {
    if (isLoading) {
      return _getLoadingView();
    }
    print('数量${_getCount()}');
    if (_getCount() <= 1) {//1 是因为有个看不清的根结点
      return NoResultWidget(
        'images/img_no_accident.png',
        "暂无数据",
        marginTop: 10,
        marginBottom: 10,
      );
    }
    return Column(
      children: [
        _listView(),
        Offstage(
          offstage: !_isShowLookAll(), //加1 是因为有个看不清的根结点
          child: ExpandOrCollapseView(expandFlag, false, (flag) {
            setState(() {
              expandFlag = flag;
            });
          }),
        )
      ],
    );
  }

  _getLoadingView() {
    return Center(
      child: Image.asset('images/timg.gif'),
    );
  }

  _listView() {
    return ListView.separated(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          return createListViewItem(index);
        },
        separatorBuilder: (context, index) {
          return Divider(
            color: Colors.grey,
            height: 0.4,
          );
        },
        itemCount: _getCount());
  }

  createListViewItem(index) {
    print("createListViewItem:$index");
    HomeTabAreaDetailObj deptObj = infoList[index];
    return Offstage(
      offstage: deptObj.nodeId == -1,
      child: Container(
//      padding: EdgeInsets.only(left: (deptObj.level - 1) * 20.0),
        child: HomeTabAreaItemWidget(deptObj, () {
          if (deptObj.areaName == 'el-icon-staff') {
            print('选择了${deptObj.areaName}');
            Navigator.pop(context, deptObj);
          } else {
            setState(() {
              recursiveConfigFlag(
                  origins, deptObj.nodeId, deptObj.isShow, !deptObj.isExpand);
              if (origins != null) {
                infoList = [];
                recursiveDeptInfos(origins, 0);
              }
            });
          }
        }),
      ),
    );
  }

  recursiveConfigFlag(
      List<HomeTabAreaDetailObj> nodes, targetId, showFlag, expandFlag) {
    if (nodes == null) {
      return;
    }
    nodes.forEach((dept) {
      if (dept.nodeId == targetId) {
        dept.isShow = showFlag;
        dept.isExpand = expandFlag;
        if (dept.child != null) {
          dept.child.forEach((o) {
            o.isShow = expandFlag;
            dept.isExpand = expandFlag;
          });
          print(1);
          if (!expandFlag) {
            recursiveCollapse(dept.child);
          }
          print(2);
        }
      } else {
        if (dept.child != null && dept.child.length != 0) {
          recursiveConfigFlag(dept.child, targetId, showFlag, expandFlag);
        }
      }
    });
  }

  recursiveDeptInfos(List<HomeTabAreaDetailObj> depts, int initLevel) {
    if (depts == null) {
      return;
    }
    initLevel++;
    print("大小:${depts.length}");
    depts.forEach((dept) {
      dept.level = initLevel;
      if (dept.level == 1 || dept.isShow) {
        infoList.add(dept);
        print("添加dept${dept.areaName},initLevel:$initLevel");
      }
      if (dept.child != null && dept.child.length != 0) {
        recursiveDeptInfos(dept.child, initLevel);
      }
    });
  }

  recursiveCollapse(List<HomeTabAreaDetailObj> nodes) {
    if (nodes == null || nodes.length == 0) {
      return;
    }
    nodes.forEach((o) {
      o.isShow = false;
      o.isExpand = false;
      recursiveCollapse(o.child);
    });
  }

  _requestAreaInfo() async {
//    infoList = [];
    if (isRequesting == true) {
      return;
    }
    isRequesting = true;
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(context, HomeHttpUrl.HOME_AREA_SUMMARY_URL,
        params, new NetListenerImpl(onSuccess, onError));
  }

  _getTabItem(name) {
    return Expanded(
        child: Container(
      height: 40,
      alignment: Alignment.center,
      child: Text(
        name,
        style: TextStyle(color: ColorList.BLACK_45),
      ),
    ));
  }

  _isShowLookAll() {
    return infoList != null && infoList.length > threshold;
  }

  _getCount() {
    if (!expandFlag && infoList != null && infoList.length > threshold) {
      return threshold;
    }
    return infoList?.length ?? 0;
  }

  void onSuccess(Response response) {
    isRequesting = false;
//    if(infoList != null && infoList.length > 0){
//      return;
//    }
    print("调用成功");
    setState(() {
      print("setState");
//      infoList.clear();
//      origins.clear();
      isLoading = false;
      if (response != null && response.data != null) {
        HomeTabAreaInfoRes res = HomeTabAreaInfoRes.fromJson(response.data);
        if (res != null && res.data != null) {
          if (res != null && res.data != null) {
            List<HomeTabAreaDetailObj> gChildren = [];
            res.data.forEach((element) {
//              element.nodeId = -1;
              gChildren.add(element);
            });
            HomeTabAreaDetailObj obj = HomeTabAreaDetailObj(
                areaName: "整体", nodeId: -1, child: gChildren);
            if(infoList != null && infoList.length > 0){
              cacheList = [];
              logList([obj]);
              infoList.forEach((element) {
                TreeNodeCacheInfo cacheInfo = cacheList.firstWhere(
                        (item) => element.nodeId == item.nodeId,
                    orElse: () => null);
                if(cacheInfo != null){
                  element.personCount = cacheInfo.personCount;
                  element.carCount = cacheInfo.carCount;
                }
              });
            }else{
              origins = [obj];
//            origins = res.data;
              print("orgins数量");
              print(origins.length);
              if (origins != null) {
                origins.forEach((dept) {
                  recursiveConfigFlag(
                      origins, dept.nodeId, dept.isShow, !dept.isExpand);
                  print("recursiveDeptInfos");
                  recursiveDeptInfos(origins, 0);
                });
              }
            }
          }
        }
      }
    });
  }

  void onError(CommonRes errorRes) {
    isRequesting = false;
  }

  refresh() async {
    setState(() {
//      isLoading = true;
    });
    await _requestAreaInfo();
  }

  showLoading() {
    setState(() {
      origins = [];
      infoList = [];
      isLoading = true;
    });
  }

  logList(List<HomeTabAreaDetailObj> list) {
    if (list != null) {
      list.forEach((element) {
        TreeNodeCacheInfo cacheInfo =
            TreeNodeCacheInfo(element.nodeId, element.personCount,element.carCount);
        cacheList.add(cacheInfo);
        print('${element.areaName}-${element.isExpand}-${element.isShow}');
        if (element != null &&
            element.child != null &&
            element.child.length > 0) {
          logList(element.child);
        }
      });
    }
  }
}
